package com.wxw.BaseLibrary.tool;

import java.io.*;

/**
 * Created by david on 2017-11-28.
 */
public class FileUtil {

    public static boolean isExists(String path) {
        try {
            File file = new File(path);
            return file.exists();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    //读文件，返回字符串
    public static String ReadFile(String path){
//	    File file = new File(path);
        BufferedReader reader = null;
//	    String laststr = "";
        StringBuilder sb = new StringBuilder();
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), "UTF-8"));

            //System.out.println("以行为单位读取文件内容，一次读一整行：");
//		    reader = new BufferedReader(new FileReader(file));
            String tempString = null;
//		    int line = 1;
            //一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                //显示行号
//	    	 	System.out.println("line " + line + ": " + tempString);
//	      		laststr = laststr + tempString;
//	      		line ++;
                sb.append(tempString);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
//	    return laststr;
        return sb.toString();
    }
    /**
     * 把字符串写到文件
     * @param filePath
     * @param sets
     * @throws IOException
     */
    public static void writeFile(String filePath, String sets) throws IOException {
        FileWriter fw = new FileWriter(filePath);
        PrintWriter out = new PrintWriter(fw);
        out.write(sets);
        out.println();
        fw.close();
        out.close();
    }

    public static void createDirectory(String path) {
        try {
            final File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static File getTempFile(String fileName) {
        int po = fileName.lastIndexOf("/");
        if (po>0 && po<fileName.length()) {
            return getTempFile(fileName.substring(0, po), fileName.substring(po+1));
        } else {
            return getTempFile(SystemTool.getSDCardPath(), fileName);
        }
    }

    public static File getTempFile(String sPath, String fileName) {
        // 指定文件路径为 外部存储 即sdcard。 文件夹名字为 项目包名。
        final File path = new File(sPath);
        if (!path.exists()) {
            path.mkdir();
        }
        return new File(path, fileName);
    }

    /**
     * 复制单个文件
     * @param oldPath String 原文件路径 如：c:/fqf.txt
     * @param newPath String 复制后路径 如：f:/fqf.txt
     * @return boolean
     */
    public static boolean copyFile(String oldPath, String newPath) {
        boolean isok = true;
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1024];
                int length;
                while ( (byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    //System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                fs.flush();
                fs.close();
                inStream.close();
            }else{
                isok = false;
            }
        } catch (Exception e) {
            // System.out.println("复制单个文件操作出错");
            // e.printStackTrace();
            isok = false;
        }
        return isok;
    }


    /**
     * 复制整个文件夹内容
     * @param oldPath String 原文件路径 如：c:/fqf
     * @param newPath String 复制后路径 如：f:/fqf/ff
     * @return boolean
     */
    public static boolean copyFolder(String oldPath, String newPath) {
        boolean isok = true;
        try {
            (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
            File a=new File(oldPath);
            String[] file=a.list();
            File temp=null;
            for (int i = 0; i < file.length; i++) {
                if(oldPath.endsWith(File.separator)){
                    temp=new File(oldPath+file[i]);
                }else{
                    temp=new File(oldPath+File.separator+file[i]);
                }
                if(temp.isFile()){
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath + "/" +
                            (temp.getName()).toString());
                    byte[] b = new byte[1024 * 5];
                    int len;
                    while ( (len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if(temp.isDirectory()){//如果是子文件夹
                    copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
                }
            }
        }catch (Exception e) {
            isok = false;
        }
        return isok;
    }

    public static boolean deleteFile(String path){
        boolean isok = true;
        try{
            File file = new File(path);
            isok = file.delete();
        }catch (Exception e){
            isok = false;
        }
        return isok;
    }

    public static boolean deleteFiles(String path, final String filter) {
        return deleteFiles(path, new FileFilter() {
            @Override
            public boolean accept(File file) {
                return file.getPath().contains(filter);
            }
        });
    }

    public static boolean deleteFiles(String path, final FileFilter filter) {
        boolean isok = true;
        try {
            File file = new File(path);
            if (file.isFile()) {
                isok = deleteFile(path);
            } else {
                File[] files = file.listFiles(filter);
                for (File f : files) {
                    isok = isok && f.delete();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            isok = false;
        }
        return isok;
    }

    public static String joinPath(String... paths) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("/");
        for (String path : paths) {
            path = path.startsWith("\\")?path.substring(1):path;
            path = path.startsWith("/")?path.substring(1):path;
            if (path.endsWith("\\") || path.endsWith("/")) {
                buffer.append(path);
            } else {
                buffer.append(path).append("/");
            }
        }
        return buffer.toString();
    }

    public static int getFileCount(String path) {
        try {
            File file = new File(path);
            if (file.isFile()) {
                return file.exists()?1:0;
            } else {
                File[] files = file.listFiles();
                if (files != null) {
                    return files.length;
                } else {
                    return 0;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}
